<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理</title>
    <!-- 引入Element UI的样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        .container {
            height: 98vh;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        .fixed-header {
            position: sticky;
            top: 0;
            background: white;
            z-index: 1000;
            padding-bottom: 10px;
            border-bottom: 1px solid #e0e0e0;
        }

        .fixed-footer {
            position: sticky;
            bottom: 0;
            background: white;
            z-index: 1000;
            padding: 10px;
            border-top: 1px solid #e0e0e0;
            display: flex;
            justify-content: center;
        }

        .content {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
            display: flex;
            flex-direction: column;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
            justify-content: center;
        }

        .centered-table {
            width: 98%;
            margin: 0 auto;
            flex: 1;
            display: flex;
            flex-direction: column;
        }
        
        /* 角色标签样式 */
        .role-tag {
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 12px;
        }
        .role-admin {
            background-color: #409EFF;
            color: white;
        }
        .role-user {
            background-color: #67C23A;
            color: white;
        }
        .role-disabled {
            background-color: #F56C6C;
            color: white;
        }
        
        /* 导航菜单样式 */
        .nav-menu {
            padding: 10px 0;
            display: flex;
            gap: 20px;
        }
        .nav-link {
            text-decoration: none;
            color: #409EFF;
            font-weight: bold;
            padding: 5px 10px;
            border-radius: 4px;
        }
        .nav-link:hover {
            background-color: #ecf5ff;
        }
    </style>
</head>
<body>
<!-- 引入Vue.js和Element UI的JavaScript库 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<div id="app" class="container">
    <div class="fixed-header">
        <!-- 导航菜单 -->
        <div class="nav-menu">
            <a href="/book/overview" class="nav-link">图书管理</a>
            <a href="/user/management" class="nav-link">用户管理</a>
            <a href="/book/borrow" class="nav-link">借阅图书</a>
        </div>
        
        <!-- 添加用户按钮 -->
        <div style="margin-bottom: 10px;">
            <el-button type="primary" @click="showAddUserDialog">添加用户</el-button>
        </div>
        
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <el-form-item label="用户名">
                <el-input v-model="searchForm.username" placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item label="真实姓名">
                <el-input v-model="searchForm.name" placeholder="真实姓名"></el-input>
            </el-form-item>
            <el-form-item label="电子邮箱">
                <el-input v-model="searchForm.email" placeholder="电子邮箱"></el-input>
            </el-form-item>
            <el-form-item label="角色">
                <el-select v-model="searchForm.role" placeholder="请选择角色">
                    <el-option label="全部" value=""></el-option>
                    <el-option label="管理员" :value="0"></el-option>
                    <el-option label="普通用户" :value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">查询</el-button>
            </el-form-item>
        </el-form>
    </div>

    <div class="content">
        <!-- 用户列表 -->
        <div class="centered-table">
            <el-table :data="users" style="width: 100%; height: 100%;" stripe border :header-cell-style="{textAlign: 'center'}" :cell-style="{textAlign: 'center'}">
                <el-table-column prop="id" label="用户ID" width="80" align="center"></el-table-column>
                <el-table-column prop="username" label="用户名" width="120" align="center"></el-table-column>
                <el-table-column prop="name" label="真实姓名" width="120" align="center"></el-table-column>
                <el-table-column prop="phone" label="电话号码" width="120" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.phone || '未填写' }}
                    </template>
                </el-table-column>
                <el-table-column prop="email" label="电子邮箱" width="180" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.email || '未填写' }}
                    </template>
                </el-table-column>
                <el-table-column label="角色" width="120" align="center">
                    <template slot-scope="scope">
                        <span v-if="!scope.row.enabled" class="role-tag role-disabled">已禁用</span>
                        <span v-else-if="scope.row.role === 0" class="role-tag role-admin">管理员</span>
                        <span v-else-if="scope.row.role === 1" class="role-tag role-user">普通用户</span>
                        <span v-else>未知</span>
                    </template>
                </el-table-column>
                <el-table-column prop="createdAt" label="创建时间" width="180" align="center"></el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template slot-scope="scope">
                        <el-button 
                            v-if="scope.row.enabled" 
                            type="danger" 
                            size="mini" 
                            @click="disableUser(scope.row.id)"
                        >禁用</el-button>
                        <el-button 
                            v-else 
                            type="success" 
                            size="mini" 
                            @click="enableUser(scope.row.id)"
                        >启用</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>

    <div class="fixed-footer">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
    </div>
    
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addUserDialogVisible">
        <el-form :model="addUserForm" ref="addUserForm" :rules="userRules" label-width="100px">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="addUserForm.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="addUserForm.password" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item label="真实姓名" prop="name">
                <el-input v-model="addUserForm.name" placeholder="请输入真实姓名"></el-input>
            </el-form-item>
            <el-form-item label="电话号码" prop="phone">
                <el-input v-model="addUserForm.phone" placeholder="请输入电话号码"></el-input>
            </el-form-item>
            <el-form-item label="电子邮箱" prop="email">
                <el-input v-model="addUserForm.email" placeholder="请输入电子邮箱"></el-input>
            </el-form-item>
            <el-form-item label="角色" prop="role">
                <el-select v-model="addUserForm.role" placeholder="请选择角色">
                    <el-option label="管理员" :value="0"></el-option>
                    <el-option label="普通用户" :value="1"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="addUserDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitAddUserForm">确 定</el-button>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            // 自定义验证方法
            const validateUsername = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入用户名'));
                } else {
                    // 检查用户名是否存在
                    axios.get(`/users/check-username?username=${value}`)
                        .then(response => {
                            if (response.data.data) {
                                callback(new Error('用户名已存在'));
                            } else {
                                callback();
                            }
                        })
                        .catch(error => {
                            console.error('检查用户名失败:', error);
                            callback(new Error('检查用户名失败'));
                        });
                }
            };
            
            const validateEmail = (rule, value, callback) => {
                if (value === '') {
                    callback();
                } else {
                    // 检查邮箱格式
                    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (!emailRegex.test(value)) {
                        callback(new Error('邮箱格式不正确'));
                        return;
                    }
                    
                    // 检查邮箱是否存在
                    axios.get(`/users/check-email?email=${value}`)
                        .then(response => {
                            if (response.data.data) {
                                callback(new Error('电子邮箱已被使用'));
                            } else {
                                callback();
                            }
                        })
                        .catch(error => {
                            console.error('检查电子邮箱失败:', error);
                            callback(new Error('检查电子邮箱失败'));
                        });
                }
            };
            
            return {
                searchForm: {
                    username: '',
                    name: '',
                    email: '',
                    role: ''
                },
                users: [],
                currentPage: 1,
                pageSize: 10,
                total: 0,
                addUserDialogVisible: false,
                addUserForm: {
                    username: '',
                    password: '',
                    name: '',
                    phone: '',
                    email: '',
                    role: 1
                },
                userRules: {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                        { validator: validateUsername, trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 6, message: '密码长度不少于6个字符', trigger: 'blur' }
                    ],
                    name: [
                        { required: true, message: '请输入真实姓名', trigger: 'blur' }
                    ],
                    email: [
                        { validator: validateEmail, trigger: 'blur' }
                    ],
                    role: [
                        { required: true, message: '请选择角色', trigger: 'change' }
                    ]
                }
            };
        },
        created() {
            this.fetchData();
        },
        methods: {
            fetchData() {
                // 构建查询参数
                const params = {
                    page: this.currentPage,
                    pageSize: this.pageSize,
                    username: this.searchForm.username || undefined,
                    name: this.searchForm.name || undefined,
                    email: this.searchForm.email || undefined,
                    role: this.searchForm.role === '' ? undefined : this.searchForm.role
                };
                
                // 发送请求获取用户列表
                axios.get('/users/page', { params })
                    .then(response => {
                        if (response.data.status === '200') {
                            this.users = response.data.data.list;
                            this.total = response.data.data.total;
                        } else {
                            this.$message.error(response.data.message || '获取用户列表失败');
                        }
                    })
                    .catch(error => {
                        console.error('获取用户列表失败:', error);
                        this.$message.error('获取用户列表失败');
                    });
            },
            onSearch() {
                this.currentPage = 1;
                this.fetchData();
            },
            handleSizeChange(val) {
                this.pageSize = val;
                this.fetchData();
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.fetchData();
            },
            showAddUserDialog() {
                this.addUserForm = {
                    username: '',
                    password: '',
                    name: '',
                    phone: '',
                    email: '',
                    role: 1
                };
                this.addUserDialogVisible = true;
            },
            submitAddUserForm() {
                this.$refs.addUserForm.validate(valid => {
                    if (valid) {
                        // 发送添加用户请求
                        axios.post('/users', this.addUserForm)
                            .then(response => {
                                if (response.data.status === '200') {
                                    this.$message.success('添加用户成功');
                                    this.addUserDialogVisible = false;
                                    this.fetchData();
                                } else {
                                    this.$message.error(response.data.message || '添加用户失败');
                                }
                            })
                            .catch(error => {
                                console.error('添加用户失败:', error);
                                this.$message.error('添加用户失败');
                            });
                    } else {
                        return false;
                    }
                });
            },
            disableUser(userId) {
                this.$confirm('确定要禁用该用户吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const request = {
                        id: userId,
                        enabled: false
                    };
                    
                    // 发送更新用户状态请求
                    axios.put('/users/status', request)
                        .then(response => {
                            if (response.data.status === '200') {
                                this.$message.success('用户已禁用');
                                this.fetchData();
                            } else {
                                this.$message.error(response.data.message || '禁用用户失败');
                            }
                        })
                        .catch(error => {
                            console.error('禁用用户失败:', error);
                            this.$message.error('禁用用户失败');
                        });
                }).catch(() => {
                    // 用户取消操作
                });
            },
            enableUser(userId) {
                this.$confirm('确定要启用该用户吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'info'
                }).then(() => {
                    const request = {
                        id: userId,
                        enabled: true
                    };
                    
                    // 发送更新用户状态请求
                    axios.put('/users/status', request)
                        .then(response => {
                            if (response.data.status === '200') {
                                this.$message.success('用户已启用');
                                this.fetchData();
                            } else {
                                this.$message.error(response.data.message || '启用用户失败');
                            }
                        })
                        .catch(error => {
                            console.error('启用用户失败:', error);
                            this.$message.error('启用用户失败');
                        });
                }).catch(() => {
                    // 用户取消操作
                });
            }
        }
    });
</script>
</body>
</html> 